package deibay.server.backend.clients;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.messages.Message;
import deibay.network.IFrontEnd;
import deibay.server.backend.ServerManager;
import deibay.server.eventargs.SendMessageEventArg;
import deibay.server.events.SendMessageEvent;
import deibay.users.User;

/**
 * @author   Joel Cordeiro
 */
public class Session {
	
	protected User user = null;
	protected IFrontEnd communicator = null;		
	protected Date lastActivity = null;
	protected LinkedBlockingQueue<Message> waiting = null;
	
	public Session(IFrontEnd server, User user)
	{
		this.communicator = server;				
		this.user = user;	
		this.lastActivity = new Date(System.currentTimeMillis());
		waiting = new LinkedBlockingQueue<Message>();
	}	
	
	public String getUsername()
	{
		return this.user.getId();
	}
	
	public void recoverSession(IFrontEnd server)
	{
		this.communicator = server;
		Message message = null;
		do {
			message = waiting.poll();
			if(message!=null)
				ServerManager.getInstance().getEventManager().fireEvent(new SendMessageEvent(new SendMessageEventArg(getUser(), getServerFrontEnd(), message)));
		}while(message!=null);
		DeibayLogger.getInstance().getLog().log(Level.INFO, "Foi recuperada a sessao do utilizador ["+user.getId()+"]\n");
	}
		
	public User getUser()
	{
		return user;
	}
		
	public IFrontEnd getServerFrontEnd()
	{
		return this.communicator;
	}
	
	public synchronized void sendMessage(Message message)
	{
		try {
			communicator.handleMsg(user, message);
		} catch (RemoteException e) {
			System.out.println("ERROR: "+e.getLocalizedMessage());
		}	
	}	
	
	public void close()
	{
			
	}

	public Date getLastActivity() {
		return lastActivity;
	}

	public void updateActivity(long l) {		
		lastActivity = new Date(l);
	}
	
	public void saveMessage(Message message)
	{
		waiting.offer(message);
	}
}
